package com.qingsong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qingsong.constant.ML;
import com.qingsong.dto.CommentInsertDTO;
import com.qingsong.dto.CommentPageDTO;
import com.qingsong.dto.CommentUpdateDTO;
import com.qingsong.entity.Comment;
import com.qingsong.entity.User;
import com.qingsong.exception.ServiceException;
import com.qingsong.feign.UserFeign;
import com.qingsong.mapper.CommentMapper;
import com.qingsong.result.Result;
import com.qingsong.service.CommentService;
import com.qingsong.vo.CommentSimpleListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import static com.qingsong.entity.table.CommentTableDef.COMMENT;
import static com.qingsong.entity.table.SeckillDetailTableDef.SECKILL_DETAIL;

/**
 * 评论表 服务层实现。
 *
 * @author qingsong
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "comment")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>  implements CommentService{
    @Autowired
    private UserFeign userFeign;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(CommentInsertDTO dto) {
        // 组装 entity 实体类
        Comment comment = BeanUtil.copyProperties(dto, Comment.class);
        // 父菜单赋值
        if (ObjectUtil.isNull(dto.getPid())) {
            comment.setPid(ML.Menu.ROOT_ID);
        }
        User user = userFeign.select(dto.getFkUserId()).getData();
        if(ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        comment.setNickname(user.getNickname());
        comment.setCreated(LocalDateTime.now());
        comment.setUpdated(LocalDateTime.now());
        return mapper.insert(comment) > 0;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Comment select(Long id) {
        RelationManager.addQueryRelations("episode");
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<CommentSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .withRelations()
                .listAs(CommentSimpleListVO.class);
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Page<Comment> page(CommentPageDTO dto) {
        QueryChain<Comment> queryChain = QueryChain.of(mapper);
        // pid 条件
        Long pid = dto.getPid();
        if (ObjectUtil.isNotNull(pid)) {
            queryChain.where(COMMENT.PID.eq(pid));
        }
        // episodeId 条件
        Long episodeId = dto.getFkEpisodeId();
        if (ObjectUtil.isNotNull(episodeId)) {
            queryChain.where(COMMENT.FK_EPISODE_ID.eq(episodeId));
        }
        // userId 条件
        Long userId = dto.getFkUserId();
        if (ObjectUtil.isNotNull(userId)) {
            queryChain.where(COMMENT.FK_USER_ID.eq(userId));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(CommentUpdateDTO dto) {
        // 组装 entity 实体类
        Comment comment = BeanUtil.copyProperties(dto, Comment.class);
        Result<User> user = userFeign.select(dto.getFkUserId());
        if(ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        comment.setNickname(user.getData().getNickname());
        comment.setUpdated(LocalDateTime.now());
        return UpdateChain.of(comment).where(COMMENT.ID.eq(comment.getId())).update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        // 查询文章评论ID和全部子评论ID
        // select id from comment where pid=? or id=?
        List<Long> deleteIds = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.eq(id))
                .or(COMMENT.ID.eq(id))
                .listAs(Long.class);

        // 删除 COMMENT 表中的记录
        // delete from comment where id in(?)
        return UpdateChain.of(mapper)
                .where(COMMENT.ID.in(deleteIds))
                .remove();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        // 查询文章评论ID和全部子评论ID
        // select id from comment where pid in(?) or id in(?)
        //SELECT COMMENT.ID FROM COMMENT WHERE COMMENT.PID IN (<ids>) OR COMMENT.ID IN (<ids>)
        List<Long> deleteIds = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.in(ids))
                .or(COMMENT.ID.in(ids))
                .objListAs(Long.class);

        // 删除 COMMENT 表中的记录
        // delete from comment where id in(?)
        return UpdateChain.of(mapper)
                .where(COMMENT.ID.in(deleteIds))
                .remove();
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteByUserId(Long userId) {
        // 查询该用户的所有评论ID列表
        List<Long> commentIds = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.FK_USER_ID.eq(userId))
                .listAs(Long.class);

        // 无评论记录
        if (CollUtil.isEmpty(commentIds)) {
            return true;
        }

        // 查询子评论ID列表
        List<Long> subCommentIds = QueryChain.of(mapper).select(COMMENT.ID)
                .where(COMMENT.PID.in(commentIds))
                .listAs(Long.class);

        // 组合父评论和子评论的ID列表
        if (CollUtil.isNotEmpty(subCommentIds)) {
            commentIds.addAll(subCommentIds);
        }

        // 删除评论
        return mapper.deleteBatchByIds(commentIds) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public  boolean deleteByUserIds(List<Long> userIds){

        List<Long> commentIds = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.FK_USER_ID.in(userIds))
                .objListAs(Long.class);


        List<Long> ids = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.in(commentIds))
                .or(COMMENT.ID.in(commentIds))
                .objListAs(Long.class);


        return UpdateChain.of(mapper)
                .where(COMMENT.ID.in(ids))
                .remove();
    }

}
